package android.vstore.activities;

import gin.dev.update.DownloadQuere;
import gin.dev.update.DownloadTask;
import gin.dev.update.IOnDownload;
import gin.dev.update.Installation;

import java.io.File;
import java.util.ArrayList;

import com.appvn2014.appstorevn.R;
import com.appvn2014.appstorevn.R.id;
import com.appvn2014.appstorevn.R.layout;
import com.appvn2014.appstorevn.R.menu;
import com.nostra13.universalimageloader.core.imageaware.ImageAware;
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;

import DTO.ImageDTO;
import DTO.ProductDTO;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.PopupMenu;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.vstore.fragment.PageSectionFragment;
import android.vstore.fragment.PageSectionFragment.CustomAdapterVerticalProduct;
import android.vstore.fragment.PageSectionFragment.Loader;
import android.vstore.fragment.PageSectionFragment.CustomAdapterVerticalProduct.ViewHolderProduct;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import anroid.vstore.provider.Constant;
import anroid.vstore.provider.Navigator;
import anroid.vstore.provider.UpdateSttListThread;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class SceneItemListActivity extends BaseActivity implements OnItemClickListener, OnScrollListener {
	String type = "";
	private ListView lv_lstProds;
	public ArrayList<ProductDTO> _lstItem = new ArrayList<ProductDTO>();;
	public boolean isProductsLoading = false;
	public boolean isNomoreLoading = false;
	public static final int REFRESH_ALL_PAGE = 10;
	private Loader loader;
	private ProgressBar pb;
	CustomAdapterVerticalProduct adapter;
	public boolean isReload;
	public int pagesize = 10;
	private String name = "";	
	Integer id ;
	public UpdateSttListThread sttlloader;

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(adapter != null)
			adapter.notifyDataSetChanged();
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_scene_item_list);
		if(getIntent().getExtras() != null)
		{
			type = getIntent().getExtras().getString(Constant.ITEM_TYPE_KEY);
			name = getIntent().getExtras().getString(Constant.ITEMLIST_TYPE_NAME);
			id = getIntent().getExtras().getInt(Constant.ITEM_ID_KEY);
		}


		
		InitActionBar();
		InitTitle();
		
		InitGUI();
		Load();
	}


	void InitTitle()
	{
		if(actionBar != null)
			actionBar.setTitle(name);
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.scene_detail_item, menu);
		return true;
	}
	

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == android.R.id.home) {
			this.finish();
			return true;
		}

		return super.onOptionsItemSelected(item);
	}
	public void InitGUI()
	{

		lv_lstProds = (ListView)findViewById(R.id.lv_prods);
		pb = (ProgressBar) findViewById(R.id.pb_listview_loading);
		pb.setVisibility(View.INVISIBLE);
		lv_lstProds.setOnItemClickListener(this);
		lv_lstProds.setOnScrollListener(this);
		lv_lstProds.setItemsCanFocus(false);
		lv_lstProds.setDividerHeight(0);
		adapter = new CustomAdapterVerticalProduct(this	, R.layout.item_list_prods	, _lstItem);
		lv_lstProds.setAdapter(adapter);

	}
	public void Load()
	{
		if(isNomoreLoading )
			return;
		if(isReload )
		{
			_lstItem.clear();
		}
		loader = new Loader();
		(loader).execute(type.toString());
		isReload = false;

	}
	public void Reload()
	{
		_lstItem = new ArrayList<ProductDTO>();
		adapter = new CustomAdapterVerticalProduct(this	, R.layout.item_list_prods	, _lstItem);
		lv_lstProds.setAdapter(adapter);
		isReload = true;
		isNomoreLoading = false;
		Load();
	}
	public class Loader extends AsyncTask<String, Void, ArrayList<ProductDTO>>{
		@Override
		protected ArrayList<ProductDTO> doInBackground(String... params) {

			ArrayList<ProductDTO> lstProds = null;
			switch (id) {
			case Constant.HORIZALLIST_COLLECTION:
				lstProds = DAO.ProductDAO.GetCollectionProds(SceneItemListActivity.this,(String)type, _lstItem.size()+pagesize);
				break;	
			case Constant.HORIZALLIST_SAMECAT:
				lstProds = DAO.ProductDAO.GetSameCatProds(SceneItemListActivity.this, (String)type,_lstItem.size()+pagesize);
				break;
			case Constant.HORIZALLIST_SAMEPUBLISHER:
				lstProds = DAO.ProductDAO.GetSamepublisherProds(SceneItemListActivity.this, (String)type,_lstItem.size()+pagesize);
				break;
			default:
				break;
			}
//			DAO.ProductDAO.GetCollectionProds(SceneItemListActivity.this,params[0],_lstItem.size()+pagesize);
			if(lstProds != null && lstProds.size() < _lstItem.size()+pagesize)
				isNomoreLoading = true;
			return lstProds;
		}      

		@Override
		protected void onPostExecute(ArrayList<ProductDTO> lstVipProd) {

			//			HideLoaderPending();
			isProductsLoading  = false;


			if(_lstItem != null && lstVipProd.size() > _lstItem.size())
			{
				int startindx = _lstItem.size();
				_lstItem.addAll(lstVipProd.subList(startindx, lstVipProd.size()));
				adapter.notifyDataSetChanged();
			}
			
			if(sttlloader == null)
			{
				sttlloader = new UpdateSttListThread(SceneItemListActivity.this, _messageHandler, _lstItem, 0, _lstItem.size());
				sttlloader.Load();
			}else
				sttlloader.LoadMore(_lstItem.size());
		}

		@Override
		protected void onPreExecute() {
			if(isProductsLoading )
			{
				this.cancel(true);
				//				HideLoaderPending();
				return;
			}
			isProductsLoading = true;
			//			ShowLoaderPending();	
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}

	protected void ShowLoaderPending()
	{		
		pb.setVisibility(View.VISIBLE);
	}
	protected void HideLoaderPending()
	{
		pb.setVisibility(View.INVISIBLE);
	}
	public class CustomAdapterVerticalProduct extends ArrayAdapter<ProductDTO>
	{
		ArrayList<ProductDTO> itemList;
		//		Boolean isInvalidated = true;
		//		String stt = getResources().getString(R.string.detail_activity_view_app);
		public Activity context;
		public LayoutInflater inflater;
		private final String TAG = "CustomAdapterProduct";

		public CustomAdapterVerticalProduct(Activity context, int textViewResource, ArrayList<ProductDTO> itemList) 
		{
			super(context, textViewResource, itemList);

			this.context = context;
			this.itemList = itemList; 

			this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		} 

		@Override 
		public int getCount() 
		{
			return itemList.size();
		}

		@Override
		public ProductDTO getItem(int position) 
		{
			return itemList.get(position);
		}

		@Override
		public long getItemId(int position) 
		{
			return 0;
		}

		public class ViewHolderProduct
		{
			public ImageView imgViewLogo;
			public ImageAware imgAwareLogo;
			public TextView txtViewTitle;
			public TextView txtViewTime;
			public TextView btnViewAppStatus;
			public ImageView ivViewMenu;
			public ImageView ivViewStatus;

			public TextView txtViewOwner;
			public TextView txtViewCat;
			public TextView txtViewSize;
			public Object lastImageUrl;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) 
		{	    	
			final ViewHolderProduct holder;
			final int pos = position;
			if(convertView == null) 
			{
				holder = new ViewHolderProduct();
				convertView = inflater.inflate(R.layout.item_list_prods, null);

				holder.imgViewLogo = (ImageView) convertView.findViewById(R.id.iv_itemlistproduct_logo);
				holder.imgAwareLogo = new ImageViewAware(holder.imgViewLogo, false);
				holder.txtViewTitle = (TextView) convertView.findViewById(R.id.tv_itemlistproduct_title);
				holder.txtViewOwner = (TextView)  convertView.findViewById(R.id.tv_itemlistproduct_publisher);
				holder.txtViewSize = (TextView)convertView.findViewById(R.id.tv_itemlistproduct_size);
				holder.txtViewCat = (TextView)convertView.findViewById(R.id.tv_itemlistproduct_cat);
				holder.btnViewAppStatus = (TextView) convertView.findViewById(R.id.btn_itemlistproduct_status);
				holder.ivViewMenu = (ImageView) convertView.findViewById(R.id.iv_itemlistproduct_menu);
				holder.ivViewStatus = (ImageView) convertView.findViewById(R.id.iv_itemlistproduct_status);
				convertView.setTag(holder);
			}
			else
				holder = (ViewHolderProduct)convertView.getTag();

			ProductDTO bean = (ProductDTO) itemList.get(position);

			if(bean == null) return convertView;

			if (holder.lastImageUrl == null || !holder.lastImageUrl.equals(bean.imgURL)
					|| holder.imgViewLogo.getDrawable() == null) {
				// refresh image
				holder.lastImageUrl = bean.imgURL;
				ImageDTO.displayImage( bean.imgURL, holder.imgAwareLogo); 
			} else {
				// do nothing, image did not change and does not need to be updated
			}

			if(itemList.get(position).isInvalidated)
			{
//				ProductDTO.VerifyAppStatus(SceneItemListActivity.this, itemList.get(position));
				itemList.get(position).isInvalidated = false;
			}
			switch (itemList.get(position).status) {
			case Constant.APP_STT_INSTALLED:
				holder.ivViewStatus.setVisibility(View.VISIBLE);
				holder.btnViewAppStatus.setVisibility(View.INVISIBLE);
				holder.ivViewStatus.setImageResource(R.drawable.ic_check);
				break;
			case Constant.APP_STT_UPDATE:
				holder.ivViewStatus.setVisibility(View.VISIBLE);
				holder.btnViewAppStatus.setText(itemList.get(position).sttStr);
				holder.btnViewAppStatus.setVisibility(View.VISIBLE);
				holder.ivViewStatus.setImageResource(R.drawable.ic_update);
				break;
			default:
				holder.btnViewAppStatus.setVisibility(View.INVISIBLE);
				holder.ivViewStatus.setVisibility(View.INVISIBLE);

				break;
			}

			holder.txtViewTitle.setText(bean.name);
			holder.txtViewOwner.setText(bean.publisher);
			holder.txtViewSize.setText(" | " + bean.size);
			holder.txtViewCat.setText(bean.category.trim());

			holder.ivViewMenu.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					PopupMenu popup = new PopupMenu(SceneItemListActivity.this, v);
					popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());
					if(itemList.get(position).status == Constant.APP_STT_NOTHING )
					{
						popup.getMenu().getItem(0).setTitle(getString(R.string.detail_activity_view_app));
						popup.getMenu().getItem(1).setTitle(getString(R.string.detail_activity_view_detail_app));
					
					}else if(itemList.get(position).status == Constant.APP_STT_DOWNLOADED )
					{
						popup.getMenu().getItem(0).setTitle(getString(R.string.detail_activity_downloaded_app));
						popup.getMenu().getItem(1).setTitle(getString(R.string.detail_activity_view_detail_app));
					}else if(itemList.get(position).status == Constant.APP_STT_UPDATE)
					{
						popup.getMenu().getItem(0).setTitle(getString(R.string.detail_activity_update_app));
						popup.getMenu().getItem(1).setTitle(getString(R.string.detail_activity_remove_app));
					}else if(itemList.get(position).status == Constant.APP_STT_DOWNLOADING)
					{
						popup.getMenu().getItem(0).setTitle(getString(R.string.detail_activity_downloading_app));
					}
					else 
					{
						popup.getMenu().getItem(0).setTitle(getString(R.string.detail_activity_open_app_name));
						popup.getMenu().getItem(1).setTitle(getString(R.string.detail_activity_remove_app));
					}
					popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
						public boolean onMenuItemClick(MenuItem item) {
							if(item.getItemId() == R.id.add1)
							{
								// Install app
								Option1(position, holder);
							}else if(item.getItemId() == R.id.add2)
							{
								Option2(position, holder);
							}
							//							Toast.makeText(activity,
							//									"You Clicked : " + item.getTitle(),
							//									Toast.LENGTH_SHORT).show();
							return true;
						}
					});

					popup.show();
				}
			});

			holder.btnViewAppStatus.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					//v.setVisibility(View.INVISIBLE);


				}


			});
			return convertView;
		}
	private void Option1(final int pos, final ViewHolderProduct holder) {
			//			final TextView btn = holder.btnViewAppStatus;

			final ProductDTO item = itemList.get(pos);
//			holder.ivViewStatus.setVisibility(View.INVISIBLE);

			if(itemList.get(pos).status == Constant.APP_STT_NOTHING || 
					itemList.get(pos).status == Constant.APP_STT_UPDATE)
			{

				itemList.get(pos).status = Constant.APP_STT_DOWNLOADING;
				String url = SceneDetailItemActivity.URL_HEADER + item.filePath;
				final String packageName = item.packageName;
				DownloadTask downloader = new DownloadTask(context, null, new IOnDownload() {

					@Override
					public void OnFinished() {
						// TODO Auto-generated method stub

						String path = Environment.getExternalStorageDirectory()
								.getAbsoluteFile()
								+ "/Download/" + packageName + ".apk";
						File file = new File(path);
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.putExtra("Position", pos);
						intent.setDataAndType(Uri.fromFile(file),
								"application/vnd.android.package-archive");
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						startActivity(intent);
						itemList.get(pos).status = Constant.APP_STT_DOWNLOADED;
						itemList.get(pos).isInvalidated = true;
						adapter.notifyDataSetChanged();
					}

					@Override
					public void OnError() {
						// TODO Auto-generated method stub
					}
				});
				DownloadQuere.Add(context, downloader, item.id, url, item.packageName);
				// Toast
			}
			if(itemList.get(pos).status == Constant.APP_STT_DOWNLOADED)
			{
				itemList.get(pos).status = Constant.APP_STT_INSTALLING;
				// install app
				String path = Environment.getExternalStorageDirectory()
						.getAbsoluteFile()
						+ "/Download/" + item.packageName + ".apk";
				if(Installation.Install(context, path) == false)
				{
					Log.i("TAG", "Error when open app" + item.packageName);
				}

			}
			if(itemList.get(pos).status == Constant.APP_STT_INSTALLED)
			{
				
				// open app
				if(Installation.OpenApp(context, item.packageName) == false)
				{
					Log.i("TAG", "Error when open app" + item.packageName);
				}
			}
			itemList.get(pos).isInvalidated = true;
		}
	    private void Option2(final int pos, final ViewHolderProduct holder) {
			//			final TextView btn = holder.btnViewAppStatus;

			final ProductDTO item = itemList.get(pos);

			if(itemList.get(pos).status == Constant.APP_STT_NOTHING ||
					itemList.get(pos).status == Constant.APP_STT_DOWNLOADED )
			{
				Navigator.toDetailItem(SceneItemListActivity.this, itemList.get(pos).id);
			}
			if(itemList.get(pos).status == Constant.APP_STT_INSTALLED|| 
					itemList.get(pos).status == Constant.APP_STT_UPDATE)
			{
				Uri uri = Uri.fromParts("package", item.packageName, null);

				Intent it = new Intent(Intent.ACTION_DELETE, uri);

				startActivity(it);
			}
			itemList.get(pos).isInvalidated = true;
		}
	}
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
		if(_lstItem != null && !isProductsLoading)
		{
			if(_lstItem.size()-2 > firstVisibleItem && _lstItem.size()-2 < firstVisibleItem+visibleItemCount)
			{
				Load();
			}
		}
	}
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		Navigator.toDetailItem(SceneItemListActivity.this, _lstItem.get(arg2));
	}
	public Handler _messageHandler = new Handler(){
		@Override
		public void handleMessage(Message msg)
		{
			if(msg.what == Constant.REFRESH_ALL_PAGE)
			{
				if(adapter != null)
					adapter.notifyDataSetChanged();  
			}
		}
	};
}
